package cn.pku.ss.fa.ui.component;

import java.io.File;

import javax.naming.InitialContext;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zul.Popup;
import org.zkoss.zul.Window;

import cn.pku.ss.fa.bean.AlbumBean;
import cn.pku.ss.fa.sessionbean.AlbumManagerLocal;
import cn.pku.ss.fa.ui.Common;
import cn.pku.ss.fa.ui.URLStrategy;

/**
 * @author SirX
 */
public class CreateAlbumWindowComponent extends Window {

	public CreateAlbumWindowComponent() {
		Session session = Executions.getCurrent().getDesktop().getSession();
		this.userId = (Integer)session.getAttribute(Common.USER_ID);
		this.userRealName = (String)session.getAttribute(Common.USER_REAL_NAME);
		this.createAlbumPopup = (Popup)session.getAttribute(Common.CREATE_ALBUM_POPUP);
	}
	
	public Popup getCreateAlbumPopup() {
		return this.createAlbumPopup;
	}
	
	public boolean createAlbum(String albumName, String albumDescription) {
		AlbumBean albumBean = new AlbumBean();
		albumBean.setName(albumName);
		albumBean.setDescription(albumDescription);
		albumBean.setUserId(userId);
		albumBean.setUserRealName(userRealName);
		albumBean.setURL( URLStrategy.getAlbumURL(userId, URLStrategy.generateRandomId()) );

		int albumId;
		//RPC:
		try {
			InitialContext ctx = new InitialContext();
			AlbumManagerLocal albumDao = (AlbumManagerLocal)ctx.lookup("FriendsAnywhere/AlbumManager/local");
			albumId = albumDao.createAlbum(albumBean);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		if( albumId==Integer.MIN_VALUE ) {  //failed
			return false;
		}
		//create directories:
		String path = Common.getWebRootRealPath() + albumBean.getURL();
		File file = new File(path);
		if( !file.mkdirs() ) {
			System.out.println( "create: "+path+" failed" );
			return false;
		}
		return true;
	}

	//////////////////////////////////////////////////////////////////////////////

	private int userId;
	private String userRealName;
	private Popup createAlbumPopup;
	
}
